package com.yupi.yoj.aop;

import cn.hutool.json.JSONUtil;
import com.yupi.yoj.common.ErrorCode;
import com.yupi.yoj.exception.ThrowUtils;
import com.yupi.yoj.model.entity.User;
import com.yupi.yoj.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if (token == null || !isValidToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    private boolean isValidToken(String token) {
//        错误的
     /*   // 此处添加token验证逻辑
        try {
            ThrowUtils.throwIf(token == null, ErrorCode.NOT_LOGIN_ERROR, "token为空");
            Claims claims = jwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            String reToken = jwtUtil.createJWT(subject);
            if (!token.equals(reToken)) {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }*/
        return true; // 示例中简化为始终返回true
    }
}

